package org.wattdepot.cli.commands;

import java.util.List;
import javax.xml.datatype.XMLGregorianCalendar;
import org.wattdepot.client.BadXmlException;
import org.wattdepot.client.MiscClientException;
import org.wattdepot.client.NotAuthorizedException;
import org.wattdepot.client.ResourceNotFoundException;
import org.wattdepot.client.WattDepotClient;
import org.wattdepot.util.tstamp.Tstamp;

/**
 *Provides the listPower command.
 * 
 * @author David Joel Lazaro
 */
public class PowerCommand implements Command {

  /**
   * Calls the listPower method.
   * 
   * @param userInput The user input.
   * @param client The WattDepotClient
   * @return Returns the method call with the proper parameters.
   */
  public String doCommand(List<String> userInput, WattDepotClient client) {
    return listPower(userInput, client);
  }

  /**
   * Prints the power generated (or consumed) by the source at the given timestamp. The power value
   * is interpolated if there is no corresponding sensor data instance.
   * 
   * @param commandParam The input from user.
   * @param client The WattDepotClient
   * @return Returns the generated/consumed power of the source.
   */
  private String listPower(List<String> commandParam, WattDepotClient client) {
    StringBuffer buff = new StringBuffer();
    SourceChecker check = new SourceChecker();
    TStampChecker stampCheck = new TStampChecker();
    if (!check.sourceChecker(commandParam.get(2), client)) {
      return "";
    }

    try {
      if (!stampCheck.checkTStamp(commandParam.get(4))) {
        return "ERROR: Timestamp error.";
      }
      XMLGregorianCalendar tstamp = Tstamp.makeTimestamp(commandParam.get(4));

      if (commandParam.get(1).equalsIgnoreCase("generated")) {
        buff.append("Power Generated: ");
        buff.append(client.getPowerGenerated(commandParam.get(2), tstamp));
      }
      else if (commandParam.get(1).equalsIgnoreCase("consumed")) {
        buff.append("Power Consumed: ");
        buff.append(client.getPowerConsumed(commandParam.get(2), tstamp));
      }
    }
    catch (NotAuthorizedException e) {
      e.printStackTrace();
    }
    catch (ResourceNotFoundException e) {
      System.out.println("Error: Requested timestamp " + commandParam.get(4) + " for the source "
          + commandParam.get(2) + " not found.");
      return "";
    }
    catch (BadXmlException e) {
      e.printStackTrace();
    }
    catch (MiscClientException e) {
      e.printStackTrace();
    }
    catch (Exception e) {
      e.printStackTrace();
    }
    return buff.toString();
  }

}
